package com.wanger.swc.util.messagePush.test;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author: wanger
 * @Date: 2025/2/10 17:32
 * @Description:
 */
@Slf4j
public class SseClient {

    public static void main(String[] args) {
        try {
            // 设置 SSE URL
            URL url = new URL("http://localhost:2000/sw/sseSendMessTest/notification/1");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置连接类型为 'text/event-stream'
            connection.setRequestProperty("Accept", "text/event-stream");
            connection.setConnectTimeout(1000000);  // 设置连接超时
            connection.setReadTimeout(3000000);    // 设置读取超时

            // 开始连接
            connection.connect();

            // 读取推送的事件数据
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String data;
                while ((data = reader.readLine()) != null) {
                    // 输出接收到的每一行数据
                    if (data.startsWith("data:")) {
                        JSONObject jsonObject = JSON.parseObject(data.substring(5));
                        log.info(JSON.toJSONString(jsonObject, JSONWriter.Feature.PrettyFormat));
                    }
                }
            }

            // 关闭连接
            connection.disconnect();
        } catch (IOException e) {
            log.error("出错了！", e);
        }
    }
}
